package org.shell.commands;

import java.util.Vector;
import org.shell.commands.exceptions.CommandException;

public class InputCommand extends Command {

    private Object[] parameters;

    public InputCommand(String input) throws CommandException {
        if (input != null) {
            splitCommand(input);
        } else {
            throw new CommandException("command is null");
        }
    }

    private void splitCommand(String input) throws CommandException {
        if (input.contains(" ")) {
            commandName = input.substring(0, input.indexOf(" "));
            input = input.substring(input.indexOf(" ") + 1, input.length());
            parameters = splitParams(input);
        } else {
            commandName = input;
        }
        if (!testCommandName(commandName)) {
            throw new CommandException("Wrong command name: " + commandName);
        }
    }

    public Object[] getParameters() {
        return parameters;
    }

    private Object[] splitParams(String input) {
        Vector<Object> params = new Vector<Object>();
        StringBuilder param = new StringBuilder();
        boolean apostrophe = false;
        for (int i = 0; i < input.length(); i++) {
            if (apostrophe) {
                if (input.charAt(i) == '\"' || input.charAt(i) == '\'') {
                    params.add(param.toString());
                    param = new StringBuilder();
                    apostrophe = false;
                } else {
                    param.append(input.charAt(i));
                }
            } else {
                if (input.charAt(i) == ' ') {
                    params.add(param.toString());
                    param = new StringBuilder();
                } else if (input.charAt(i) == '\'' || input.charAt(i) == '\"') {
                    if (param.length() > 0) {
                        params.add(param.toString());
                        param = new StringBuilder();
                    }
                    apostrophe = true;
                } else {
                    param.append(input.charAt(i));
                }
            }
        }
        if(param.length() > 0) {
            params.add(param.toString());
        }
        return params.toArray(new Object[0]);
    }
}
